package com.tust.controller;

import com.tust.domain.Article;
import com.tust.domain.Comment;
import com.tust.domain.Message;
import com.tust.domain.User;
import com.tust.paging.CommentListPaging;
import com.tust.paging.CommentPaging;
import com.tust.service.ArticleService;
import com.tust.service.CommentService;
import com.tust.service.MessageService;
import com.tust.service.UserService;
import com.tust.trans.CommentDetail;
import com.tust.trans.CommentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.*;

/*控制层Controller评论类*/
@Controller
public class CommentController {
    /*自动注入Service用户接口*/
    @Autowired
    private UserService userService;
    /*自动注入Service评论接口*/
    @Autowired
    private CommentService commentService;
    /*自动注入Service消息接口*/
    @Autowired
    private MessageService messageService;
    /*自动注入Service贴文接口*/
    @Autowired
    private ArticleService articleService;

    /********************************************管理端请求********************************************/

    /*用于分页功能*/
    private List<Comment> selectComments = null;//存储完整查询结果
    private CommentPaging commentPaging = new CommentPaging();//分页类

    private int ifShowAllComment = 1;//保存当前数据表显示状态(默认显示所有数据)

    /**
     * 查询所有评论
     * 响应"/selectAllComment.do"请求
     * @return List<Comment> 返回评论集合
     */
    @ResponseBody
    @RequestMapping("/manage/selectAllComment.do")
    public List<Comment> selectAllComment() {
        List<Comment> comments = commentService.selectAllComment();

        selectComments = comments;//存储完整查询结果
        commentPaging.recordCount = selectComments.size();
        commentPaging.pageCount = selectComments.size() % commentPaging.maxRecordNum == 0 ? selectComments.size() / commentPaging.maxRecordNum : selectComments.size() / commentPaging.maxRecordNum + 1;
        commentPaging.currentPage = 0;//当前页码为0

        System.out.println("查询所有评论: size:" + comments.size());
        return commentPaging.showPageContent(selectComments);//调用分页显示方法
    }

    /**
     * 查询所有待审核评论
     * 响应"/selectAllBeCheckedComment.do"请求
     * @return List<Comment> 返回评论集合
     */
    @ResponseBody
    @RequestMapping("/manage/selectAllBeCheckedComment.do")
    public List<Comment> selectAllBeCheckedComment() {
        List<Comment> comments = commentService.selectAllBeCheckedComment();

        selectComments = comments;//存储完整查询结果
        commentPaging.recordCount = selectComments.size();
        commentPaging.pageCount = selectComments.size() % commentPaging.maxRecordNum == 0 ? selectComments.size() / commentPaging.maxRecordNum : selectComments.size() / commentPaging.maxRecordNum + 1;
        commentPaging.currentPage = 0;//当前页码为0

        System.out.println("查询所有待审核评论: size:" + comments.size());
        return commentPaging.showPageContent(selectComments);//调用分页显示方法
    }

    /**
     * 查询评论
     * 响应"/selectComment.do"请求
     * @param selectOption 选择项
     * @param selectContent 选择内容
     * @return List<Comment> 返回评论集合
     */
    @ResponseBody
    @RequestMapping("/manage/selectComment.do")
    public List<Comment> selectComment(String selectOption, String selectContent) {
        List<Comment> comments = null;

        if (selectOption.equals("评论ID")) comments = commentService.selectCommentByComID(Integer.valueOf(selectContent));//按评论ID查找评论记录
        else if (selectOption.equals("用户ID")) comments = commentService.selectCommentByUID(Integer.valueOf(selectContent));//按用户ID查找评论记录
        else if (selectOption.equals("贴文ID")) comments = commentService.selectCommentByArtID(Integer.valueOf(selectContent));//按贴文ID查找评论记录
        else if (selectOption.equals("用户名")) comments = commentService.selectCommentByUname(selectContent);//按用户名查找评论记录
        else if (selectOption.equals("评论内容")) comments = commentService.selectCommentByComContent(selectContent);//按评论内容查找评论记录
        else if (selectOption.equals("审核状态")) comments = commentService.selectCommentByComStatus(Integer.valueOf(selectContent));//按审核状态查找评论记录
        else if (selectOption.equals("评论时间")) comments = commentService.selectCommentByComTime(selectContent);//按评论时间查找评论记录

        selectComments = comments;//存储完整查询结果
        commentPaging.recordCount = selectComments.size();
        commentPaging.pageCount = selectComments.size() % commentPaging.maxRecordNum == 0 ? selectComments.size() / commentPaging.maxRecordNum : selectComments.size() / commentPaging.maxRecordNum + 1;
        commentPaging.currentPage = 0;//当前页码为0

        System.out.println("查询评论: selectOption:" + selectOption + " selectContent:" + selectContent + " size:" + comments.size());
        return commentPaging.showPageContent(selectComments);//调用分页显示方法
    }

    /**
     * 分页上一页
     * 响应"/preCommentPage.do"请求
     * @return List<Comment> 返回评论集合
     */
    @ResponseBody
    @RequestMapping("/manage/preCommentPage.do")
    public List<Comment> preCommentPage() {
        if (!commentPaging.isFirstPage()) {//当前页不是第一页
            commentPaging.currentPage--;//当前页码-1
        }
        return commentPaging.showPageContent(selectComments);//调用分页显示方法
    }

    /**
     * 分页下一页
     * 响应"/nextCommentPage.do"请求
     * @return List<Comment> 返回评论集合
     */
    @ResponseBody
    @RequestMapping("/manage/nextCommentPage.do")
    public List<Comment> nextCommentPage() {
        if (!commentPaging.isLastPage(selectComments)) {//当前页不是最后一页
            commentPaging.currentPage++;//当前页码+1
        }
        return commentPaging.showPageContent(selectComments);//调用分页显示方法
    }

    /**
     * 分页最前页
     * 响应"/topCommentPage.do"请求
     * @return List<Comment> 返回评论集合
     */
    @ResponseBody
    @RequestMapping("/manage/topCommentPage.do")
    public List<Comment> topCommentPage() {
        commentPaging.currentPage = 0;//当前页码为0
        return commentPaging.showPageContent(selectComments);//调用分页显示方法
    }

    /**
     * 分页最尾页
     * 响应"/endCommentPage.do"请求
     * @return List<Comment> 返回评论集合
     */
    @ResponseBody
    @RequestMapping("/manage/endCommentPage.do")
    public List<Comment> endCommentPage() {
        commentPaging.currentPage = commentPaging.pageCount - 1;//当前页码为总分页数量-1
        return commentPaging.showPageContent(selectComments);//调用分页显示方法
    }

    /**
     * 获取当前分页信息
     * 响应"/getCommentPageInfo.do"请求
     * @param tableStatus 数据表状态
     * @return pageInfo 返回分页信息
     */
    @ResponseBody
    @RequestMapping("/manage/getCommentPageInfo.do")
    public CommentPaging getCommentPageInfo(int tableStatus) {
        ifShowAllComment = tableStatus;
        return commentPaging;
    }

    /**
     * 审核通过评论
     * 响应"/passComment.do"请求
     * @param ComID 评论ID
     * @return msg 返回前端校验信息
     */
    @ResponseBody
    @RequestMapping("/manage/passComment.do")
    public String passComment(int ComID) {
        String msg = null;
        Message message = new Message();

        if (commentService.updateCommentByComIDCheck(ComID, 1) == 1) {//审核通过评论成功
            msg = "passCommentSuccess";

            //发送消息
            List<Comment> comments = commentService.selectCommentByComID(ComID);//找到评论
            if (comments.size() == 0) return "databaseFalse";
            message.setMsgReceiver(comments.get(0).getUID());
            message.setArtID(comments.get(0).getArtID());
            message.setMsgContent("您的评论：'" + comments.get(0).getComContent() + "'已通过审核");
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date();//获取当前时间
            message.setMsgTime(formatter.format(date));
            message.setMsgFromUser(0);
            message.setMsgIsReaded(0);
            if (messageService.insertMessage(message) != 1) return "databaseFalse";//发送消息
        } else {//审核通过评论失败
            msg = "passCommentFalse";
        }

        System.out.println("评论通过审核: " + msg);
        return msg;
    }

    /**
     * 审核不通过评论
     * 响应"/notPassComment.do"请求
     * @param ComID 评论ID
     * @return msg 返回前端校验信息
     */
    @ResponseBody
    @RequestMapping("/manage/notPassComment.do")
    public String notPassComment(int ComID) {
        String msg = null;
        Message message = new Message();

        if (commentService.updateCommentByComIDCheck(ComID, -1) == 1) {//审核不通过评论成功
            msg = "notPassCommentSuccess";

            //禁言等级+1
            List<Comment> comments = commentService.selectCommentByComID(ComID);//找到评论
            if (comments.size() == 0) return "databaseFalse";
            int UID = comments.get(0).getUID();//获得用户ID
            List<User> users = userService.selectUserByUID(UID);//找到用户
            if (users.size() == 0) return "databaseFalse";
            int UbanLevel = users.get(0).getUbanLevel();//获得禁言等级
            users.get(0).setUbanLevel(UbanLevel + 1);//禁言等级+1

            if (UbanLevel + 1 > 3) {//若禁言等级>3，禁言用户，发送消息
                //禁言时间+1天
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Calendar calendar = new GregorianCalendar();
                Date date = new Date();//获取当前时间
                calendar.setTime(date);
                calendar.add(calendar.DATE,1);//当前时间+1天
                date = calendar.getTime();
                if (userService.updateUserBan(UID, -1, formatter.format(date)) != 1) return "databaseFalse";//禁言时间+1

                //发送消息
                message.setMsgReceiver(UID);
                message.setArtID(-1);
                message.setMsgContent("非常抱歉，您的评论：'" + comments.get(0).getComContent() + "'未通过审核\n由于您的发言不当，已被禁言1天");
                date = new Date();//获取当前时间
                message.setMsgTime(formatter.format(date));
                message.setMsgFromUser(0);
                message.setMsgIsReaded(0);
            } else {//发送消息
                message.setMsgReceiver(UID);
                message.setArtID(-1);
                message.setMsgContent("非常抱歉，您的评论：'" + comments.get(0).getComContent() + "'未通过审核");
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date();//获取当前时间
                message.setMsgTime(formatter.format(date));
                message.setMsgFromUser(0);
                message.setMsgIsReaded(0);
            }
            if (messageService.insertMessage(message) != 1) return "databaseFalse";//发送消息
        } else {//审核不通过评论失败
            msg = "notPassCommentFalse";
        }

        System.out.println("评论不通过审核: " + msg);
        return msg;
    }

    /**
     * 删除评论
     * 响应"/deleteComment.do"请求
     * @param ComID 评论ID
     * @return msg 返回前端校验信息
     * 删除步骤
     *   1.评论内容置'该评论已被删除'
     *   2.向用户ID发送信息
     */
    @ResponseBody
    @RequestMapping("/manage/deleteComment.do")
    public String deleteComment(int ComID) {
        String msg = null;
        Message message = new Message();

        //在删除前获得评论内容
        List<Comment> comments = commentService.selectCommentByComID(ComID);//找到评论
        if (comments.size() == 0) return "databaseFalse";
        String ComContent = comments.get(0).getComContent();

        if (commentService.updateCommentByComIDDelete(ComID) == 1) {//评论删除成功
            msg = "deleteCommentSuccess";

            //发送消息
            message.setMsgReceiver(comments.get(0).getUID());
            message.setArtID(-1);
            message.setMsgContent("非常抱歉，您的评论：'" + ComContent + "'已被管理员删除");
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date();//获取当前时间
            message.setMsgTime(formatter.format(date));
            message.setMsgFromUser(0);
            message.setMsgIsReaded(0);
            if (messageService.insertMessage(message) != 1) return "databaseFalse";//发送消息
        } else {//评论删除失败
            msg = "deleteCommentFalse";
        }

        System.out.println("删除评论: " + msg);
        return msg;
    }

    /**
     * 刷新页面
     * 响应"/refreshComment.do"请求
     * @return List<Comment> 返回评论集合
     */
    @ResponseBody
    @RequestMapping("/manage/refreshComment.do")
    public List<Comment> refreshComment() {
        //禁言操作后需要存储新的完整查询结果
        List<Comment> comments = null;

        if (ifShowAllComment == 1) comments = commentService.selectAllComment();
        else comments = commentService.selectAllBeCheckedComment();

        selectComments = comments;//存储完整查询结果
        commentPaging.recordCount = selectComments.size();
        commentPaging.pageCount = selectComments.size() % commentPaging.maxRecordNum == 0 ? selectComments.size() / commentPaging.maxRecordNum : selectComments.size() / commentPaging.maxRecordNum + 1;

        return commentPaging.showPageContent(selectComments);//调用分页显示方法
    }

    /**
     * 展示评论
     * 响应"/showComment.do"请求
     * @param ArtID 贴文ID
     * @return List<Comment> 返回评论集合
     */
    @ResponseBody
    @RequestMapping("/manage/showComment.do")
    public List<Comment> showComment(int ArtID) {
        List<Comment> comments = commentService.selectCommentByArtID(ArtID);//按贴文ID查找评论记录

        System.out.println("展示评论: size:" + comments.size());
        return comments;
    }

    /********************************************客户端请求********************************************/

    /*用于分页功能*/
    private List<CommentList> selectCommentLists = null;//存储完整查询结果
    private CommentListPaging commentListPaging = new CommentListPaging();//分页类

    /**
     * 查询所有个人评论列表
     * 响应"/searchAllPerComList.do"请求
     * @param UID 用户ID
     * @return List<CommentList> 返回评论列表集合
     */
    @ResponseBody
    @RequestMapping("/searchAllPerComList.do")
    public List<CommentList> searchAllPerComList(int UID) {
        List<Comment> comments = commentService.selectCommentByUID(UID);//按用户ID查找评论记录

        List<CommentList> commentLists = new ArrayList<>();
        List<Article> articles = new ArrayList<>();
        CommentList commentList = null;
        Article article = null;
        int i = 0;
        for (Comment comment: comments) {
            i = 0;
            for (Article art : articles) {
                if (art.getArtID() == comment.getArtID()){
                    article = art;
                    i = 1;
                    break;
                }
            }
            if (i == 0) {
                article = articleService.selectArticleByArtID(comment.getArtID()).get(0);
                articles.add(article);
            }

            commentList = new CommentList();
            commentList.setArtID(comment.getArtID());
            commentList.setArtCategory(article.getArtCategory());
            commentList.setArtTitle(article.getArtTitle());
            if (comment.getComStatus() == 0) commentList.setComContent("评论待审核");
            else commentList.setComContent(comment.getComContent());
            commentList.setComTime(comment.getComTime());
            commentList.setComStatus(comment.getComStatus());

            commentLists.add(commentList);
        }

        selectCommentLists = commentLists;//存储完整查询结果
        commentListPaging.recordCount = selectCommentLists.size();
        commentListPaging.pageCount = selectCommentLists.size() % commentListPaging.maxRecordNum == 0 ? selectCommentLists.size() / commentListPaging.maxRecordNum : selectCommentLists.size() / commentListPaging.maxRecordNum + 1;
        commentListPaging.currentPage = 0;//当前页码为0

        System.out.println("查询所有个人评论列表: size:" + commentLists.size());
        return commentListPaging.showPageContent(selectCommentLists);//调用分页显示方法
    }

    /**
     * 查询个人评论列表
     * 响应"/searchPerComList.do"请求
     * @param UID 用户ID
     * @param searchContent 搜索内容
     * @return List<CommentList> 返回评论列表集合
     */
    @ResponseBody
    @RequestMapping("/searchPerComList.do")
    public List<CommentList> searchPerComList(int UID, String searchContent) {
        List<Comment> comments = commentService.selectCommentByUID(UID);//按用户ID查找评论记录

        List<CommentList> commentLists = new ArrayList<>();
        List<Article> articles = new ArrayList<>();
        CommentList commentList = null;
        Article article = null;
        int i = 0;
        for (Comment comment: comments) {
            if (articleService.selectArticleByArtID(comment.getArtID()).get(0).getArtTitle().contains(searchContent)) {
                i = 0;
                for (Article art : articles) {
                    if (art.getArtID() == comment.getArtID()) {
                        i = 1;
                        article = art;
                        break;
                    }
                }
                if (i == 0) {
                    article = articleService.selectArticleByArtID(comment.getArtID()).get(0);
                    articles.add(article);
                }

                commentList = new CommentList();
                commentList.setArtID(comment.getArtID());
                commentList.setArtCategory(article.getArtCategory());
                commentList.setArtTitle(article.getArtTitle());
                if (comment.getComStatus() == 0) commentList.setComContent("评论待审核");
                else commentList.setComContent(comment.getComContent());
                commentList.setComTime(comment.getComTime());
                commentList.setComStatus(comment.getComStatus());

                commentLists.add(commentList);
            }
        }

        selectCommentLists = commentLists;//存储完整查询结果
        commentListPaging.recordCount = selectCommentLists.size();
        commentListPaging.pageCount = selectCommentLists.size() % commentListPaging.maxRecordNum == 0 ? selectCommentLists.size() / commentListPaging.maxRecordNum : selectCommentLists.size() / commentListPaging.maxRecordNum + 1;
        commentListPaging.currentPage = 0;//当前页码为0

        System.out.println("查询个人评论列表: size:" + commentLists.size());
        return commentListPaging.showPageContent(selectCommentLists);//调用分页显示方法
    }

    /**
     * 分页下一页
     * 响应"/nextCommentListPage.do"请求
     * @return List<CommentList> 返回评论列表集合
     */
    @ResponseBody
    @RequestMapping("/nextCommentListPage.do")
    public List<CommentList> nextCommentListPage() {
        if (!commentListPaging.isLastPage(selectCommentLists)) {//当前页不是最后一页
            commentListPaging.currentPage++;//当前页码+1
        } else return new ArrayList<>();
        return commentListPaging.showPageContent(selectCommentLists);//调用分页显示方法
    }

    /**
     * 分页最前页
     * 响应"/topCommentListPage.do"请求
     * @return List<CommentList> 返回评论列表集合
     */
    @ResponseBody
    @RequestMapping("/topCommentListPage.do")
    public List<CommentList> topCommentListPage() {
        commentListPaging.currentPage = 0;//当前页码为0
        return commentListPaging.showPageContent(selectCommentLists);//调用分页显示方法
    }

    /**
     * 展示贴文评论
     * 响应"/showArtComment.do"请求
     * @param ArtID 贴文ID
     * @return List<CommentDetail> 返回评论详情集合
     */
    @ResponseBody
    @RequestMapping("/showArtComment.do")
    public List<CommentDetail> showArtComment(int ArtID) {
        List<Comment> comments = commentService.selectPassCommentByArtID(ArtID);//按贴文ID查找审核通过评论记录

        List<CommentDetail> commentDetails = new ArrayList<>();
        CommentDetail commentDetail = null;
        for (Comment comment : comments) {
            commentDetail = new CommentDetail();
            commentDetail.setUID(comment.getUID());
            commentDetail.setUname(userService.selectUserByUID(comment.getUID()).get(0).getUname());
            commentDetail.setComContent(comment.getComContent());
            commentDetail.setComTime(comment.getComTime());

            commentDetails.add(0, commentDetail);
        }

        System.out.println("展示评论: size:" + comments.size());
        return commentDetails;
    }

    /**
     * 插入评论
     * 响应"/insertComment.do"请求
     * @param UID 用户ID
     * @param ArtID 贴文ID
     * @param ComContent 评论内容
     * @return msg 返回前端校验信息
     */
    @ResponseBody
    @RequestMapping("/insertComment.do")
    public String insertComment(int UID, int ArtID, String ComContent) {
        if (userService.selectUserByUID(UID).get(0).getUbanLevel() == -1) return "userBaning";

        String msg = null;
        Message message = new Message();
        Comment comment = new Comment();

        comment.setUID(UID);
        comment.setArtID(ArtID);
        comment.setComContent(ComContent);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();//获取当前时间
        comment.setComTime(formatter.format(date));

        if (commentService.insertComment(comment) == 1) {
            msg = "insertCommentSuccess";//评论插入成功

            //发送消息
            message.setMsgSender(UID);
            message.setMsgReceiver(articleService.selectArticleByArtID(ArtID).get(0).getUID());
            message.setArtID(ArtID);
            message.setMsgContent("您的贴文被" + userService.selectUserByUID(UID).get(0).getUname() + "评论");
            date = new Date();//获取当前时间
            message.setMsgTime(formatter.format(date));
            message.setMsgFromUser(1);
            message.setMsgIsReaded(0);
            if (messageService.insertMessage(message) != 1) return "databaseFalse";//发送消息
        } else msg = "insertCommentFalse";//评论插入失败

        System.out.println("插入评论: " + msg);
        return msg;
    }
}
